package me.wangqu.weiyouqu.web.rest.util;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import me.wangqu.weiyouqu.domain.Captcha;
import me.wangqu.weiyouqu.web.rest.util.constant.Constant;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Random;

/**
 * Created by arcticfox on 4/26/16.
 */
public class CaptchaUtil {

    public static String randomCode() {
        return randomCode(1000, 9999);
    }

    public static String randomCode(int from, int to) {
        return String.valueOf(from + new Random().nextInt(to - from));
    }

    /**
     * 发送注册短信通知
     * @param phone
     * @param code
     * @return
     */
    public static AlibabaAliqinFcSmsNumSendResponse sendSmsRegister(String phone, String code) {
        return CaptchaUtil.sendSms(phone, code, Constant.CAPTCHA_TYPE_REGISTER);
    }

    /**
     * 发送修改密码短信通知
     * @param phone
     * @param code
     * @return
     */
    public static AlibabaAliqinFcSmsNumSendResponse sendSmsPasswordReset(String phone, String code) {
        return CaptchaUtil.sendSms(phone, code, Constant.CAPTCHA_TYPE_PASSWORD_RESET);
    }

    public static AlibabaAliqinFcSmsNumSendResponse sendSms(String phone, String code, Integer type) {
        JSONObject params = new JSONObject();
        try {
            // 当前模板只接受字符串值
            params.put("code", code);
            params.put("product", Constant.PRODUCT_NAME);
            params.put("time", "5");
        } catch (JSONException e) {
            params = null;
        } finally {
            if (params != null) {
                TaobaoClient client = new DefaultTaobaoClient(Constant.SMS_URL, Constant.SMS_APP_KEY, Constant.SMS_APP_SECRET);
                AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
                req.setSmsType("normal");
                req.setSmsParamString(params.toString());
                req.setRecNum(phone);
                if (Constant.CAPTCHA_TYPE_REGISTER == type) {
                    req.setSmsFreeSignName(Constant.SMS_SIGN_NAME_REGISTER);
                    req.setSmsTemplateCode(Constant.SMS_TEMPLATE_CODE_REGISTER);
                } else if (Constant.CAPTCHA_TYPE_PASSWORD_RESET == type) {
                    req.setSmsFreeSignName(Constant.SMS_SIGN_NAME_CHANGE);
                    req.setSmsTemplateCode(Constant.SMS_TEMPLATE_CODE_PASSWORD_RESET);
                }
                try {
                    return client.execute(req);
                } catch (ApiException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
